/****************************************************************************
 * 2024.9 ADMIN-20230317Z
 ****************************************************************************/

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using QFramework;
using UnityEngine.U2D;

namespace QFramework.Monk
{
	public partial class LevelUpPanel : UIElement, IController
	{
		public List<Button> btns = new List<Button>();
		private ExpUpSystem expUpSystem;
		private ResLoader  resLoader;
		private SpriteAtlas atlas;
		private void Awake()
		{
			expUpSystem = this.GetSystem<ExpUpSystem>();
			resLoader = ResLoader.Allocate();
			atlas = resLoader.LoadSync<SpriteAtlas>("Icon");
		}

		public Sprite LoadSprite(string name)
		{
			return atlas.GetSprite(name);
		}
		
		public void RefreshBtns()
		{
			ClearBtns();
			foreach (var expUpItem in expUpSystem.expUpItems)
			{
				var btn = LevelUpTemplate.InstantiateWithParent(LevelUpRoot).Self(button =>
				{	
					var buttonCache = button;
					buttonCache.onClick.AddListener((() =>
					{
						Time.timeScale = 1;
						AudioKit.PlaySound("ability_level_up");
						expUpItem.OnUpgrade();
						this.Hide();
						
					}));
					buttonCache.GetComponentInChildren<Text>().text =
						string.Format(expUpItem.mSkillItem.Desc, expUpItem.mSkillItem.Value);
					buttonCache.transform.Find("Icon").GetComponent<Image>().sprite = LoadSprite(expUpItem.mSkillItem.Icon);

				}).Show();
				btns.Add(btn);
			}
		}

		private void ClearBtns()
		{
			foreach (var button in btns)
			{
				button.gameObject.DestroySelfGracefully();
			}
			btns.Clear();
		}
		

		public IArchitecture GetArchitecture()
		{
			return AppStart.Interface;
		}
		
		protected override void OnBeforeDestroy()
		{
			resLoader.Recycle2Cache();
			resLoader = null;
			atlas = null;
		}
	}
}